package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

import po.Student;
import service.ContactService;
import view.ContactDialog;
import view.ContactFrame;

public class ContactControllerListener implements ActionListener{
	private ContactService contactService;
	private ContactFrame contactFrame;
	private ContactDialog contactDialog;
	private int selRow;
	
	public ContactControllerListener() {
		super();
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		if("searchStudentDialog".equals(e.getActionCommand())) { 
			String str = JOptionPane.showInputDialog(contactFrame, "输入学号");
			if(str != null && !"".equals(str)) { //str不为null且str内容不为""
				if(str.matches("^2\\d{11}$")){
					long studentNo = Long.parseLong(str);
					Student student = new Student();
					student.setStudentNo(studentNo);
					Student result = contactService.getStudent(studentNo);
					contactFrame.showSearchResult(result);
				}else {
					JOptionPane.showMessageDialog(contactFrame, "输入的不是学号","输入错误",JOptionPane.ERROR_MESSAGE);
				}
			}
		}else if("addStudentDialog".equals(e.getActionCommand())){
			contactDialog = new ContactDialog(contactFrame,1,null);
			 
		}
		else if("ensure1".equals(e.getActionCommand())) {
			Student student = contactDialog.getInstance();
			contactService.addStudent(student);
			JOptionPane.showMessageDialog(contactFrame, "添加"+student.getStudentNo()+"号学生成功！");
			contactDialog.dispose();
			contactFrame.refresh();
		}
		else if("deleteStudentDialog".equals(e.getActionCommand())) {
			long studentNo = Long.parseLong(contactFrame.getText2().getText().toString());
			contactService.deleteStudent(studentNo);
			JOptionPane.showMessageDialog(contactFrame, "删除"+studentNo+"号学生成功！");
			contactFrame.refresh();
		}
		else if("updateStudentDialog".equals(e.getActionCommand())) {
			long studentNo = Long.parseLong(contactFrame.getText2().getText().toString());
			Student student = contactService.getStudent(studentNo);
			contactDialog = new ContactDialog(contactFrame,2,student);
		}
		else if("ensure2".equals(e.getActionCommand())) {
			
			Student student = contactDialog.getInstance();
			contactService.updateStudent(student);
			JOptionPane.showMessageDialog(contactFrame, "更新"+student.getStudentNo()+"号学生成功！");
			contactDialog.dispose();
			contactDialog.refresh(student.getStudentNo());
		}
		
	}
	public ContactService getContactService() {
		return contactService;
	}
	public void setContactService(ContactService contactService) {
		this.contactService = contactService;
	}
	public ContactFrame getContactFrame() {
		return contactFrame;
	}
	public void setContactFrame(ContactFrame contactFrame) {
		this.contactFrame = contactFrame;
	}
	
}
